//
//  ShareWebViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-3-11.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "ShareWebViewController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
#import "MainTabBarController.h"
@interface ShareWebViewController ()

@end

@implementation ShareWebViewController
@synthesize m_ShareType;
@synthesize m_ContentID;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc
{
    [_NavBtt release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"微博分享"];
    
    m_titleBttBarItem = [[MainTabBarController setTitle:@"微博分享"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _SelfWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44)];
    [self.view addSubview:_SelfWebView];
    _SelfWebView.delegate = self;
    

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewDidAppear:(BOOL)animated
{
    NSString* tTokenStr = nil;
    if (m_ShareType == 0) {
        tTokenStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"tokensina"];
    }else if(m_ShareType == 1){
        tTokenStr =[[NSUserDefaults standardUserDefaults] objectForKey:@"tencent"];
    }
    if ([tTokenStr length] > 0) {
        [self requesShare];
    }else{
        [self requestListData];
    }
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}


-(void) requestListData
{
    [self addHudLoad];
    NSString* tURLStr =@"";
    if (m_ShareType == 0) {
        tURLStr = [NSString stringWithFormat:@"%@ac=oauthAuthorize&app=ihuikao&target=%@",RequestCurrentURL,@"sina"];
    }else if(m_ShareType == 1){
        tURLStr = [NSString stringWithFormat:@"%@ac=oauthAuthorize&app=ihuikao&target=%@",RequestCurrentURL,@"tencent"];
    }
    
    tURLStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)tURLStr, nil, nil, kCFStringEncodingUTF8);
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestListFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestListFinish:)];
    [tRequestPage startAsynchronous];

}

-(void) requestListFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestListFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            _RequestURL = [[NSString alloc] initWithString:[tRealDataDic objectForKey:@"url"]];
            _CallBack = [[NSString alloc] initWithString:[tRealDataDic objectForKey:@"callback"]];
            
            [_SelfWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_RequestURL]]];
        }else{
            
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:NO delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

#pragma mark-
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.absoluteString rangeOfString:_CallBack].location != NSNotFound) {
        NSLog(@"%@",request.URL.absoluteString);
        int tLocation =[request.URL.absoluteString rangeOfString:@"token="].location+6;
        NSString* tTokenStr = [request.URL.absoluteString substringWithRange:NSMakeRange(tLocation, [request.URL.absoluteString length]-tLocation)];
        NSLog(@"%@",tTokenStr);
        if (m_ShareType == 0) {
            [[NSUserDefaults standardUserDefaults] setObject:tTokenStr forKey:@"tokensina"];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:tTokenStr forKey:@"tokentencent"];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self requesShare];
    }
    return YES;
}


-(void) requesShare
{
    [self addHudLoad];
    NSString* tURLStr =@"";
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    if (m_ShareType == 0) {
        tURLStr = [NSString stringWithFormat:@"%@ac=share&app=ihuikao&target=sina&token=%@&content_type=news&content_id=%@",RequestCurrentURL,[tUserDef objectForKey:@"tokensina"],m_ContentID];
    }else if(m_ShareType == 1){
        tURLStr = [NSString stringWithFormat:@"%@ac=share&app=ihuikao&target=tencent&token=%@&content_type=news&content_id=%@",RequestCurrentURL,[tUserDef objectForKey:@"tokentencent"],m_ContentID];
    }
    
    tURLStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)tURLStr, nil, nil, kCFStringEncodingUTF8);
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestShareFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestShareFinish:)];
    [tRequestPage startAsynchronous];
    
}

-(void) requestShareFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestShareFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            int tResStatus = [[tRealDataDic objectForKey:@"result"] intValue];
            if (tResStatus == 1) {
                [tAppDel showWithCustomView:@"微博分享成功" detailText:@"" isCue:-1 delayTime:2];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [tAppDel showWithCustomView:@"微博分享失败" detailText:@"" isCue:-1 delayTime:2];
            }
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:NO delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}
@end
